package com.psychproject.web.controllers;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.psychproject.web.domains.User;
import com.psychproject.web.services.UserServices;

@Controller
@RequestMapping(value = "/user")
public class UserController {
	private @Autowired
	HttpServletRequest request;
	@Autowired
	private UserServices userServices;

	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(Model model) {
		model.addAttribute(new User());
		return "user/create";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String create(User user, BindingResult result) {
		userServices.createUser(user);
		return "redirect:/user/all";
	}

	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public String getView(@PathVariable Long id, Model model) {
		User user = userServices.findById(id);
		model.addAttribute(user);
		return "user/view";
	}

	@RequestMapping(value = "/all", method = RequestMethod.GET)
	public String all(
			@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
			Model model) {
		String pageUrl = request.getContextPath() + "/user/all";
		model.addAttribute("pageResult", userServices.paged(page, pageUrl));
		return "user/all";
	}

	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public String delete(User user, Model model) {
		userServices.delete(user);
		return "redirect:/user/all";
	}

	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String getEditForm(Long id, Model model) {
		User user = userServices.findById(id);
		model.addAttribute(user);
		return "user/edit";
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String edit(User user, Model model) {
		userServices.update(user);
		return "redirect:/user/all";
	}
}
